package com.sise.bl.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sise.bl.adapter.TypeAdapter;
import com.sise.bl.entity.Type;
import com.sise.bl.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping(value = "/type")
@SessionAttributes({"goodsTypeList","msg"})
public class TypeController {
    @Autowired
    @Qualifier("typeService")
    private TypeService typeService;

    @RequestMapping(value = "/findAll")
    @ResponseBody
    public String findAll(Model model) {
        List<Type> types = typeService.findAll();

        model.addAttribute("goodsTypeList",types);

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Type.class, new TypeAdapter());
        Gson gson = gsonBuilder.create();

        String json = gson.toJson(types);
        return json;
    }

    @RequestMapping(value = "/addGoodsType")
    public ModelAndView addGoodsType(@RequestParam("typename")String name,@RequestParam("tinfo")String info, ModelAndView modelAndView){
        Type type = new Type();
        type.setTname(name);
        type.setTinfo(info);

        int i = typeService.addType(type);
        if (i==0){
            modelAndView.addObject("msg", "添加错误，q请稍后重试！！！");
            modelAndView.setViewName("message");
            return modelAndView;
        }
        modelAndView.setViewName("/admin/addGoodsType");
        return modelAndView;
    }
}
